package oa.hleast.xswl.controller.app;


import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.result.Result;
import oa.hleast.common.upload.component.IFileService;
import oa.hleast.common.upload.config.UploadProperties;
import oa.hleast.common.web.exception.BizException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

@Api(tags = "【移动端】文件接口")
@RestController
@RequestMapping("/api.app/v1/files")
@Slf4j
@AllArgsConstructor
public class MinIOController {

    private final IFileService minIOService;
    private final UploadProperties uploadProperties;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", paramType = "form", dataType = "__file",dataTypeClass = File.class),
            @ApiImplicitParam(name = "bucketName", value = "桶名称", paramType = "query", dataType = "string",dataTypeClass = String.class)
    })
    public Result<String> upload(
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam(value = "bucketName", required = false, defaultValue = "default") String bucketName
    ) {
        return uploadFile(file, uploadProperties.getBucketName());
    }


    private Result<String> uploadFile(MultipartFile file, String bucketName) {
        try {
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String objectName = IdUtil.simpleUUID() + "." + suffix;
            String path = minIOService.putObject(bucketName, objectName, file.getInputStream());
            return Result.success(path);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }
}
